<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\FeatureStatusModel;
use App\Models\PageLinksModel;
use App\Models\UserActivityLogModel;

class Feature extends Controller
{
    public function index()
    {
        $featureStatusModel = new FeatureStatusModel();
        // 获取所有特征状态
        $features = $featureStatusModel->findAll();

        return view('feature_index', ['features' => $features]);
    }

    public function set_feature()
    {
        $featureStatusModel = new FeatureStatusModel();
        $request = service('request');
        $featureKeys = $request->getPost('feature_key');
        $featureStatuses = $request->getPost('status');

        if ($featureKeys && $featureStatuses) {
            foreach ($featureKeys as $index => $key) {
                $status = $featureStatuses[$index];
                $feature = $featureStatusModel->where('feature_key', $key)->first();
                if ($feature) {
                    $featureStatusModel->update($feature['id'], ['status' => $status]);
                }
            }
            return redirect()->back()->with('success', '特征状态更新成功');
        }

        return redirect()->back()->with('error', '更新失败，请检查输入');
    }

    public function get_feature()
    {
        $featureStatusModel = new FeatureStatusModel();
        $canEditKeywords = $featureStatusModel->where('feature_key', "can_edit_keywords")->first();
        $editKeywordStatus = $canEditKeywords["status"];

        if (0 == $editKeywordStatus) {
            return redirect()->back()->with('error', '关键词功能关闭');
        }
    }


    public function clear_page_links()
    {
        $pageLinksModel = new PageLinksModel();
        // $pageLinksModel->emptyTable();
        try {
            $pageLinksModel->emptyTable();
            return $this->response->setJSON(['status' => 'success', 'message' => '链接记录已清空']);
        } catch (\Exception $e) {
            return $this->response->setJSON(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function clear_activity_logs()
    {
        $userActivityLogModel = new UserActivityLogModel();
        // $pageLinksModel->emptyTable();
        try {
            $userActivityLogModel->emptyTable();
            return $this->response->setJSON(['status' => 'success', 'message' => '用户记录已清空']);
        } catch (\Exception $e) {
            return $this->response->setJSON(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
}